//
//  LocationManager.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/10/25.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import CoreLocation
import JZLocationConverterSwift
class LocationManager: NSObject {
    
    static let share = LocationManager()
    
    private let manager = CLLocationManager()
    
    var gcj02:CLLocationCoordinate2D?
    
    override init() {
        super.init()
        
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter = 10
        manager.pausesLocationUpdatesAutomatically = false
        
        requestAuthorization()
    }
    
    private func requestAuthorization() {
        
        let status = CLLocationManager.authorizationStatus()
        
        switch status {
            
        case .notDetermined,.restricted:
            
            manager.requestWhenInUseAuthorization()
        case .denied:
            
            IGAlertVC.show(title: nil, message: LocalizedString("location_permission_tips"), commit: (LocalizedString("setting"),{
                
                let url = URL(string: UIApplication.openSettingsURLString)
                
                UIApplication.shared.openURL(url!)
                
            }))
        default:
            
            break
        }
    }
    
    func startUpdatingLocation() {
        
        self.manager.startUpdatingLocation()
    }
}

extension LocationManager: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        if let coor = locations.last?.coordinate {
            
            JZLocationConverter.default.wgs84ToGcj02(coor) { gcj02 in
                
                self.gcj02 = gcj02
            }
        }
    }
}

extension LocationManager {
    
    class func distance(form:CLLocationCoordinate2D,to:CLLocationCoordinate2D) -> Double {
        
        let location1 = CLLocation(latitude: form.latitude, longitude: form.longitude)
        let location2 = CLLocation(latitude: to.latitude, longitude: to.longitude)
        
        return location1.distance(from: location2)
    }
}


